//
//  ZMyAddressAddVC.m
//  DistributorAB
//
//  Created by LZY on 2019/10/12.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "ZMyAddressAddVC.h"
#import "MOFSPickerManager.h"//地址选择

@interface ZMyAddressAddVC () <UITextFieldDelegate>
{
    __block BOOL _isSelectedDefault;//是否设置为默认地址
}
@property (nonatomic, strong) UITextField *tfName;//姓名
@property (nonatomic, strong) UITextField *tfPhone;//电话
@property (nonatomic, strong) UITextField *tfAddress;//地址
@property (nonatomic, strong) UITextField *tfAddressDetail;//详细地址
@property (nonatomic, strong) UIImageView *ivCycle;//勾选
@property (nonatomic, copy) NSString *addressCode;//地址编码
@end

@implementation ZMyAddressAddVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    self.view.backgroundColor = kColorWithHex(0xf2f2f2);
    _isSelectedDefault = NO;
    
    [self setupViewAction];
    
    if (self.modelEdit) {
        self.title = @"编辑地址";
        [self updateAddressData];
    }else{
        self.title = @"我的地址";
    }
}
#pragma mark - 界面布局
- (void)setupViewAction{
    UIView *viewBg = [[UIView alloc] initWithFrame:CGRectMake(0, kNaviHeight, kScreen_Width, 195)];
    viewBg.backgroundColor = kColorWithHex(0xffffff);
    [self.view addSubview:viewBg];
    
    
    UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, 70, 48)];
    lblName.text = @"姓名:";
    lblName.font = [UIFont systemFontOfSize:14];
    lblName.textColor = kColorWithHex(0x666666);
    [viewBg addSubview:lblName];
    _tfName = [[UITextField alloc] initWithFrame:CGRectMake(96, 0, kScreen_Width - 109, 48)];
    _tfName.font = [UIFont systemFontOfSize:14];
    _tfName.textColor = kColorWithHex(0x232620);
    _tfName.placeholder = @"请输入姓名";
    _tfName.delegate = self;
    [viewBg addSubview:_tfName];
    UIView *viewLineOne = [[UIView alloc] initWithFrame:CGRectMake(0, 48, kScreen_Width, 1)];
    viewLineOne.backgroundColor = kColorWithHex(0xf2f2f2);
    [viewBg addSubview:viewLineOne];
    
    UILabel *lblPhone = [[UILabel alloc] initWithFrame:CGRectMake(16, 49, 70, 48)];
    lblPhone.text = @"联系方式:";
    lblPhone.font = [UIFont systemFontOfSize:14];
    lblPhone.textColor = kColorWithHex(0x666666);
    [viewBg addSubview:lblPhone];
    _tfPhone = [[UITextField alloc] initWithFrame:CGRectMake(96, 49, kScreen_Width - 109, 48)];
    _tfPhone.font = [UIFont systemFontOfSize:14];
    _tfPhone.textColor = kColorWithHex(0x232620);
    _tfPhone.placeholder = @"请输入电话";
    _tfPhone.delegate = self;
    [viewBg addSubview:_tfPhone];
    UIView *viewLineTwo = [[UIView alloc] initWithFrame:CGRectMake(0, 97, kScreen_Width, 1)];
    viewLineTwo.backgroundColor = kColorWithHex(0xf2f2f2);
    [viewBg addSubview:viewLineTwo];
    
    UILabel *lblAddress = [[UILabel alloc] initWithFrame:CGRectMake(16, 98, 70, 48)];
    lblAddress.text = @"所在地区:";
    lblAddress.font = [UIFont systemFontOfSize:14];
    lblAddress.textColor = kColorWithHex(0x666666);
    [viewBg addSubview:lblAddress];
    _tfAddress = [[UITextField alloc] initWithFrame:CGRectMake(96, 98, kScreen_Width - 109, 48)];
    _tfAddress.font = [UIFont systemFontOfSize:14];
    _tfAddress.textColor = kColorWithHex(0x232620);
    _tfAddress.placeholder = @"请选择所在地区";
    _tfAddress.delegate = self;
    [viewBg addSubview:_tfAddress];
    UIButton *btnAddress = [UIButton buttonWithType:UIButtonTypeCustom];
    btnAddress.frame = CGRectMake(96, 98, kScreen_Width - 109, 48);
    [btnAddress addTarget:self action:@selector(btnAddressClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:btnAddress];
    UIImageView *ivArrow = [[UIImageView alloc] initWithFrame:CGRectMake(kScreen_Width - 25, 111, 12, 22)];
    ivArrow.image = imgname(@"arrow_right_icon");
    [viewBg addSubview:ivArrow];
    UIView *viewLineThree = [[UIView alloc] initWithFrame:CGRectMake(0, 146, kScreen_Width, 1)];
    viewLineThree.backgroundColor = kColorWithHex(0xf2f2f2);
    [viewBg addSubview:viewLineThree];
    
    UILabel *lblAddressDetail = [[UILabel alloc] initWithFrame:CGRectMake(16, 147, 70, 48)];
    lblAddressDetail.text = @"详细地址:";
    lblAddressDetail.font = [UIFont systemFontOfSize:14];
    lblAddressDetail.textColor = kColorWithHex(0x666666);
    [viewBg addSubview:lblAddressDetail];
    _tfAddressDetail = [[UITextField alloc] initWithFrame:CGRectMake(96, 147, kScreen_Width - 109, 48)];
    _tfAddressDetail.font = [UIFont systemFontOfSize:14];
    _tfAddressDetail.textColor = kColorWithHex(0x232620);
    _tfAddressDetail.placeholder = @"请输入详细地址";
    _tfAddressDetail.delegate = self;
    [viewBg addSubview:_tfAddressDetail];
    UIView *viewLineFour = [[UIView alloc] initWithFrame:CGRectMake(0, 195, kScreen_Width, 1)];
    viewLineFour.backgroundColor = kColorWithHex(0xf2f2f2);
    [viewBg addSubview:viewLineFour];
    
    //编辑界面 暂时去掉 设为默认地址功能
    _ivCycle = [[UIImageView alloc] initWithFrame:CGRectMake(13, 208, 20, 20)];
    _ivCycle.image = imgname(@"cycle_normal_gray_icon");
    [viewBg addSubview:_ivCycle];
    _ivCycle.hidden = YES;
    
    UILabel *lblNotice = [[UILabel alloc] initWithFrame:CGRectMake(42, 208, 90, 20)];
    lblNotice.text = @"设为默认地址";
    lblNotice.font = [UIFont systemFontOfSize:14];
    lblNotice.textColor = kColorWithHex(0x707070);
    [viewBg addSubview:lblNotice];
    lblNotice.hidden = YES;
    
    UIButton *btnDefault = [UIButton buttonWithType:UIButtonTypeCustom];
    btnDefault.frame = CGRectMake(13, 208, 119, 20);
    [btnDefault addTarget:self action:@selector(btnDefaultClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:btnDefault];
    btnDefault.hidden = YES;
    
    
    UIButton *btnOk = [UIButton buttonWithType:UIButtonTypeCustom];
    btnOk.frame = CGRectMake(28, kScreen_Height - kScaleNum(189), kScreen_Width - 56, 48);
    [btnOk setTitle:@"确认" forState:UIControlStateNormal];
    [btnOk setTitleColor:kColorWithHex(0xffffff) forState:UIControlStateNormal];
    [btnOk setBackgroundColor:kColorWithHex(0x70be68)];
    btnOk.titleLabel.font = [UIFont systemFontOfSize:16];
    [btnOk addTarget:self action:@selector(btnOkClickAction:) forControlEvents:UIControlEventTouchUpInside];
    btnOk.layer.cornerRadius = 4;
    btnOk.layer.masksToBounds = YES;
    [self.view addSubview:btnOk];
}
#pragma mark - 编辑地址更新界面
- (void)updateAddressData{
    _tfName.text = self.modelEdit.user_name;
    _tfPhone.text = self.modelEdit.phone;
    NSMutableArray *addressArray = [self.modelEdit.address componentsSeparatedByString:@" "].mutableCopy;
    _tfAddress.text = [NSString stringWithFormat:@"%@",[addressArray objectAtIndexSafe:0]];
    if (addressArray.count > 3) {
        [addressArray removeObjectsInRange:NSMakeRange(0, 3)];
    }
    _tfAddressDetail.text = [addressArray safeObjectAtIndex:1];
    if ([self.modelEdit.is_default isEqualToString:@"0"]) {
        _isSelectedDefault = NO;
        _ivCycle.image = imgname(@"cycle_normal_gray_icon");
    }else{
        _isSelectedDefault = YES;
        _ivCycle.image = imgname(@"cycle_selected_green_icon");
    }
    
    self.addressCode = self.modelEdit.province;
    self.addressCode = [self.addressCode stringByAppendingString:[NSString stringWithFormat:@"-%@",self.modelEdit.city]];
    self.addressCode = [self.addressCode stringByAppendingString:[NSString stringWithFormat:@"-%@",self.modelEdit.area]];
}

#pragma mark - 交互事件
- (void)btnOkClickAction:(UIButton *)sender{
    //去掉首尾的空格
    NSString *nameStr = [_tfName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *phoneStr = [_tfPhone.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *addressStr = [_tfAddress.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *addressDetailStr = [_tfAddressDetail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (nameStr.length < 1) {
        ShowToastWithText(@"请输入姓名");
    }else if (nameStr.length > 10){
        ShowToastWithText(@"姓名不能超过10个字");
    }else if (![HFTools validateMobile:phoneStr]){
        ShowToastWithText(@"请检查电话信息");
    }else if (addressStr.length < 1){
        ShowToastWithText(@"请选择所在地区");
    }else if (addressDetailStr.length < 1){
        ShowToastWithText(@"请输入详细地址");
    }else{
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObjectIfNotNil:nameStr forKey:@"user_name"];
        [dict setObjectIfNotNil:phoneStr forKey:@"phone"];
        addressDetailStr = [addressStr stringByAppendingString:[NSString stringWithFormat:@" %@",addressDetailStr]];
        [dict setObjectIfNotNil:addressDetailStr forKey:@"address"];
        NSArray *addressCode = [self.addressCode componentsSeparatedByString:@"-"];
        [dict setObjectIfNotNil:[addressCode objectAtIndexSafe:0] forKey:@"province"];
        [dict setObjectIfNotNil:[addressCode objectAtIndexSafe:1] forKey:@"city"];
        [dict setObjectIfNotNil:[addressCode objectAtIndexSafe:2] forKey:@"area"];
        [dict setObjectIfNotNil:_isSelectedDefault ? @"1" : @"0" forKey:@"is_default"];
        if (self.modelEdit) {
            //编辑地址
            [dict setObjectIfNotNil:self.modelEdit.Id forKey:@"id"];
            [self editAddressSubmitWithDict:dict];
        }else{
            //添加地址
            [self addAddressSubmitWithDict:dict];
        }
    }
}
//地址选择
- (void)btnAddressClickAction:(UIButton *)sender{
    kWeakSelf;
    [[MOFSPickerManager shareManger] showMOFSAddressPickerWithDefaultZipcode:@"110000-110100-110101" title:@"选择地址" cancelTitle:@"取消" commitTitle:@"确定" commitBlock:^(NSString * _Nullable address, NSString * _Nullable zipcode) {
        //北京市-北京市-东城区
        //110000-110100-110101
        weakSelf.addressCode = zipcode;
        address = [address stringByReplacingOccurrencesOfString:@"-" withString:@""];
        weakSelf.tfAddress.text = address;
    } cancelBlock:^{
        
    }];
}
//设为默认地址
- (void)btnDefaultClickAction:(UIButton *)sender{
    if (_isSelectedDefault) {
        _isSelectedDefault = NO;
        _ivCycle.image = imgname(@"cycle_normal_gray_icon");
    }else{
        _isSelectedDefault = YES;
        _ivCycle.image = imgname(@"cycle_selected_green_icon");
    }
}
#pragma mark - 添加地址
- (void)addAddressSubmitWithDict:(NSMutableDictionary *)dict{
    NSString *jsonStr = [HFTools toJSONString:dict];
    NSDictionary *param = [NSDictionary dictionaryWithObject:jsonStr forKey:@"data"];
    kWeakSelf;
    [NetWorkTool POST:addAgentAddress param:param success:^(id dic) {
        ShowToastWithText(@"添加地址成功");
        [[NSNotificationCenter defaultCenter] postNotificationName:USER_ADD_ADDRESS_SUCCESS object:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        [weakSelf saveDefaultAddress:dic];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
}
#pragma mark - 编辑地址
- (void)editAddressSubmitWithDict:(NSMutableDictionary *)dict{
    NSString *jsonStr = [HFTools toJSONString:dict];
    NSDictionary *param = [NSDictionary dictionaryWithObject:jsonStr forKey:@"data"];
    kWeakSelf;
    [NetWorkTool POST:editAgentAddress param:param success:^(id dic) {
        ShowToastWithText(@"编辑地址成功");
        [[NSNotificationCenter defaultCenter] postNotificationName:USER_ADD_ADDRESS_SUCCESS object:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        
        [weakSelf saveDefaultAddress:dic];
        
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
}
#pragma mark - 默认地址保存
- (void)saveDefaultAddress:(id)dic{
    if (_isSelectedDefault) {
        ZMyAddressModel *model = [ZMyAddressModel mj_objectWithKeyValues:[dic objectForKeyNotNil:@"data"]];
        if ([model.is_default isEqualToString:@"1"]) {
            NSData *addressData = [NSKeyedArchiver archivedDataWithRootObject:model];
            [USER_DEFAULT setObject:addressData forKey:DEFAULT_ADDRESS];
            [USER_DEFAULT synchronize];
        }
    }
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([textField isFirstResponder]) {
        if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
            
            return NO;
        }
        
        if ([self stringContainsEmoji:string]){
            ShowToastWithText(@"暂不支持输入表情符");
            return NO;
        }
    }
    return YES;
}
//表情符号的判断
- (BOOL)stringContainsEmoji:(NSString *)string {
    
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        if (0x278b <= hs && hs <= 0x2792) {
                                            //自带九宫格拼音键盘
                                            returnValue = NO;;
                                        }else if (0x263b == hs) {
                                            returnValue = NO;;
                                        }else {
                                            returnValue = YES;
                                        }
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}
#pragma mark - 判断是否是九宫格键盘
-(BOOL)isNineKeyBoard:(NSString *)string
{
    NSString *other = @"➋➌➍➎➏➐➑➒";
    int len = (int)string.length;
    for(int i=0;i<len;i++)
    {
        if(!([other rangeOfString:string].location != NSNotFound))
            return NO;
    }
    return YES;
}
#pragma mark - 判断是否含有表情(第三方键盘)
- (BOOL)hasEmoji:(NSString*)string;
{
    NSString *pattern = @"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}

@end
